package com.ddpt.permission.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.lh.center.common.base.BizServiceImpl;
import com.lh.center.permission.api.entity.Permission;
import com.lh.center.permission.api.request.PermissionQueryRequest;
import com.lh.center.permission.api.session.SessionPermission;
import com.lh.center.permission.mapper.PermissionMapper;
import com.lh.center.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author czy
 * @since 2022-04-07
 */
@Service
public class PermissionServiceImpl extends BizServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 将权限集合组装成层级结构
     * @param permissionList
     * @return
     */
    @Override
    public List<SessionPermission> buildLayerPermission(List<SessionPermission> permissionList) {
        List<SessionPermission> targetList = new ArrayList<>();
        if(CollUtil.isEmpty(permissionList)) {
            return targetList;
        }
        Map<Long, List<SessionPermission>> permiMap = permissionList.stream().collect(Collectors.groupingBy(SessionPermission::getParentId));
        for(SessionPermission permission : permiMap.get(0L)) {
            targetList.add(permission);
            buildLayerPermission(permission,permiMap);
        }
        return targetList;
    }

    private void buildLayerPermission(SessionPermission parent,Map<Long, List<SessionPermission>> permiMap) {
        List<SessionPermission> subList = permiMap.get(parent.getId());
        if(CollUtil.isNotEmpty(subList)) {
            parent.setChildren(subList);
            for(SessionPermission child : subList) {
                buildLayerPermission(child,permiMap);
            }
        }
    }

    @Override
    public List<SessionPermission> queryTree(PermissionQueryRequest queryRequest) {
        List<SessionPermission> permissionList = permissionMapper.queryListByAdminServiceAndMerchantService(queryRequest);
        return buildLayerPermission(permissionList);
    }
}
